<?php

declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\AppService\Guid;
use App\Service\Code\Normal;
use App\Service\AppService\Sign;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use App\Service\AppService\SystemCacheConfigService;

class Customs extends BasePssModel
{
    public $table = 'realtimedata';
    
    public function signdata($orderno,$sessionid,$servertime)
    {
        $add_data=  [
            'sessionID'=>$sessionid,
            'orderNo'=>$orderno,
            'serviceTime'=>$servertime,
            'status'=>0
        ];
        $res= $this->add($add_data);
        if (empty($res)) {
            return [
                'status' => Normal::FAIL,
                'msg'    => '新增失败',
            ];
        }
        $customsconfig  = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('custom');
        $order= OrderSupplier::instance()->info(['order_sn'=>$orderno]);
        if(empty($order)){
            return [
                'status' => Normal::FAIL,
                'msg'    => '未找到相关订单',
            ];
        }
        
        $apply_extends = @json_decode($order['apply_extends'],true);
        $payCode        = $apply_extends['payCommanyCode'];
        $payCommanyName = $apply_extends['payCommanyName'];
        $ordergoods= OrderSupplierGoods::instance()->rows(['order_id'=>$order['id'],'df'=>0]);
        $goods=array();
        foreach ($ordergoods as $key => $v) {
            //$goodsdata= Goods::instance()->info(['id'=>$v['goods_id']]);
            $goods[]=array('gname'=>$v['goods_name'],'itemLink'=>$customsconfig['host'].'/#/goods/goodsdetail/'.$v['goods_id']);
        }
        $serviceTime= MsecTime();
        $datas  = [];
        $datas['sessionID']=$sessionid;
        $datas['payExchangeInfoHead']= [
            'guid'              =>  Guid::getGuidOnlyValue(),
            'initalRequest'     =>  $order['apply_request'],
            'initalResponse'    =>  $order['apply_response'],
            'ebpCode'           =>  $customsconfig['ebpCode'],//电商平台代码
            'payCode'           =>  $payCode,//支付企业代码
            'payTransactionId'  =>  $order['pay_sn'],//支付流水号
            'totalAmount'       =>  (double)$order['pay_money'],//原始乘以100了,现在去掉
            'currency'          =>  '142',
            'verDept'           =>  $customsconfig['verDept'],//核验机构1-银联 2-网联 3-其他
            'payType'           =>  $customsconfig['payType'],//用户支付的类型。1-APP 2-PC 3-扫码 4-其他
            'tradingTime'       =>  (string)date("YmdHis",$order['apply_response_time']),//交易成功时间
            'note'              =>  '交易成功时间'
        ];
        $datas['payExchangeInfoLists']= [
            [
                'orderNo'       =>  $orderno,
                'goodsInfo'     =>  $goods,
                'recpAccount'   =>  $customsconfig['companyAccount'],//交易商品的卖方商户账号。电商平台自营商户应填写自营商户的收款账户；非自营电商应填写非自营商户的收款账户。
                'recpCode'      =>  $customsconfig['companyCode'],      //应填写收款企业代码（境内企业为统一社会信用代码；境外企业可不填写）
                'recpName'      =>  $customsconfig['companyName'],      //应填写收款企业名称。
            ]
        ];
        $datas['serviceTime']= (string)$serviceTime;
        $this->edit(['orderNo'=>$orderno], ['status'=>1,'signdata'=> json_encode($datas,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]);
        return [
            'status'    => Normal::SUC,
            'msg'       => '获取成功',
            'data'      => $datas
        ];
    }
    
    public function sign($orderno,$sessionid,$servertime)
    {
        $customsconfig = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('custom');
        $signdata= $this->signdata($orderno, $sessionid, $servertime);
        if($signdata['status']!= Normal::SUC){
            return $signdata;
        }
        $data= $this->arraytostring($signdata['data']);
        if($customsconfig['signType']==1){//信通签名
            $cdkjt= Sign::getInstance(
                $customsconfig['signAccount'], 
                $customsconfig['signPassword'],
                $customsconfig['ebpCode'],
                $customsconfig['ebpCode'],
                $signdata['data']['payExchangeInfoHead']['payCode']
            );
            $xml=$cdkjt->sign($data,$orderno,$customsconfig['signKeyinfo']);
            $parameter = [
                [
                    'tag'       => 'getRealtimeDataSignByXintong',
                    'uid'       => IdService::instance()->getOtherID(),
                    'url'       => $customsconfig['cbec_declare_url'],
                    'data'      => ['xml'=>$xml],
                    'method'    => 'post',
                    'format'    => 'x-www-form-urlencoded',
                    'header'    => []
                ]
            ];
            $resTask = TaskWorker::instance()->addTask($parameter);
        }elseif($customsconfig['signType']==2){//关务签名
            $parameter = [
                [
                    'tag'       => 'getRealtimeDataSignByGw',
                    'uid'       => IdService::instance()->getOtherID(),
                    'url'       => $customsconfig['signAddress'],
                    'data'      => [
                        'jsonParamStr'  =>  $data
                    ],
                    'method'    => 'post',
                    'format'    => 'json',
                    'header'    => []
                 ]
            ];
            $resTask = TaskWorker::instance()->addTask($parameter);
            $redata  = @json_decode(current($resTask)['response']['result'],true);            
            if($redata['code']==200){
                $resave=array('status'=>2,'sign'=>(string)$redata['data']);
                $this->edit(['orderNo'=>$orderno], $resave);
            }else{
                $resave=array('sign'=>(string)$redata['data']);
                $this->edit(['orderNo'=>$orderno], $resave);
            }
        }elseif($customsconfig['signType']==3){
            $parameter = [
                [
                    'tag'       => 'getRealtimeDataSignByIcClient',
                    'uid'       => IdService::instance()->getOtherID(),
                    'url'       => $customsconfig['ic_client_declare_url'],
                    'data'      => [
                        'CountersignString' => $data,
                        'code'              => $customsconfig['ebpCode'],
                    ],
                    'method'    => 'post',
                    'format'    => 'json',
                    'header'    => []
                 ]
            ];
            $resTask = TaskWorker::instance()->addTask($parameter);
            $redata  = @json_decode(current($resTask)['response']['result'],true);
            $resave = ['sign'=>(string)$redata['countersignString']];
            if($redata['code'] == Normal::SUC){
                $resave['status'] = 2;
            }
            $this->edit(['orderNo' =>$orderno], $resave);
        }
        return [
            'status' => Normal::SUC,
            'msg' => '获取成功',
        ];
    }
    
    public function arraytostring($data){
        $string='';
        $string.='"sessionID":"'.$data['sessionID'].'"||';
        $string.='"payExchangeInfoHead":"'.json_encode($data['payExchangeInfoHead'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES).'"||';
        $string.='"payExchangeInfoLists":"'.json_encode($data['payExchangeInfoLists'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES).'"||';
        $string.='"serviceTime":"'.$data['serviceTime'].'"';
        return $string;
    }
}